import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { RootState } from '../store';
import { getPathList, IPath } from 'services/path';

const namespace = 'path/list';

interface IInitialState {
  loading: boolean;
  page_num: number;
  page_size: number;
  total: number;
  pathList: IPath[];
}

const initialState: IInitialState = {
  loading: true,
  page_num: 1,
  page_size: 10,
  total: 0,
  pathList: [],
};

export const getList = createAsyncThunk(
  `${namespace}/getPathList`,
  async (params: { page_size: number; page_num: number }) => {
    const result = await getPathList(params);
    return {
      list: result?.data,
      total: result?.total,
      page_size: params.page_size,
      page_num: params.page_num,
    };
  },
);

const pathListSlice = createSlice({
  name: namespace,
  initialState,
  reducers: {
    clearPageState: () => initialState,
  },
  extraReducers: (builder) => {
    builder
      .addCase(getList.pending, (state) => {
        state.loading = true;
      })
      .addCase(getList.fulfilled, (state, action) => {
        console.log('action.....: ', action);
        state.loading = false;
        state.pathList = action.payload?.list;
        state.total = action.payload?.total;
        state.page_size = action.payload?.page_size;
        state.page_num = action.payload?.page_num;
      })
      .addCase(getList.rejected, (state) => {
        state.loading = false;
      });
  },
});

export const { clearPageState } = pathListSlice.actions;

export const selectPathList = (state: RootState) => state.pathList;

export default pathListSlice.reducer;
